import {
  accountLogin,
  accountLoginWithValidateCode,
  delegateLogin,
  delegateLogout,
} from "@/services/api";
import { logoutByChain } from "@/utils/login";
import { dynamicHeader, getUserIdentity } from "@/utils/utils";
import { notification } from "antd";
import { getLocale } from "umi";
import { Model } from "./connect";
import { Mode } from '@/constant/mode';

const locale = getLocale();

const userIdentity = getUserIdentity();
export interface LoginState {
  checkCookieRet: boolean;
}
interface Login extends Model {
  state: LoginState;
}

const login: Login = {
  namespace: "login",
  state: {
    checkCookieRet: false,
    ...userIdentity,
  },
  effects: {
    // 登录
    *login({ payload }, { call, put }) {
      const {
        userName,
        password,
        validateCodeId,
        validateCode,
        loginSuccessCallback,
        errorCallback,
      } = payload;
      try {
        let response;
        if (!_.isEmpty(validateCodeId) && !_.isEmpty(validateCode)) {
          response = yield call(accountLoginWithValidateCode, {
            userLoginName: userName,
            password,
            validateCodeId,
            validateCode,
            type: null,
          });
        } else {
          response = yield call(accountLogin, {
            userLoginName: userName,
            password,
            usertype: undefined,
          });
        }
        const { userLoginName, userToken, loginType } = response;
        if (userToken) {
          const userIdentity = {
            loginType,
            userToken: userToken,
            userLoginName: userLoginName,
            userLanguage: locale === "en-US" ? "en" : "zh_CN", // 根据国际化替换
            systemType: Mode.VEHICLE,
            delegateMode: false, // 登录时，需要init
          };
          localStorage.setItem("userIdentity", JSON.stringify(userIdentity));
          window.localStorage.setItem("username", userName);

          // 设置 request header
          dynamicHeader.current = userIdentity;

          yield put({
            type: 'global/save',
            payload: { isSelfDeveloped: userIdentity.systemType === Mode.SELF_DEVELOPED }
          })
          yield put({
            // 缓存到redux
            type: "save",
            payload: userIdentity,
          });
          loginSuccessCallback && loginSuccessCallback();
        } else {
          errorCallback && errorCallback();
          notification.error({
            duration: 3,
            message: "用户名或密码错误",
          });
        }
      } catch (error) {
        console.error(error);
      }
    },
    //用户信息写入localStorage
    *writeToLocalStorage({ payload }, { call, put, select }) {
      const {
        userLoginName,
        userToken,
        delegateMode,
        delegateCertificateId,
        delegateUserLoginName,
      } = payload;
      const userIdentity = {
        loginType: "DEFAULT_LOGIN",
        userLoginName: userLoginName,
        userToken: userToken,
        userLanguage: locale === "en-US" ? "en" : "zh_CN",
        delegateMode,
        delegateCertificateId,
        delegateUserLoginName,
      };
      localStorage.setItem("userIdentity", JSON.stringify(userIdentity));
    },
    //切换用户代理
    *delegateLogin({ payload }, { call, put, select }) {
      const { delegateCertificateId, ownerUserLoginName } = payload;
      const { userLoginName } = yield select((state) => state.login);
      const delegateMode = true;
      const response = yield call(delegateLogin, {
        ...payload,
      });

      if (response) {
        const token = response.token;
        yield put({
          type: "writeToLocalStorage",
          payload: {
            delegateMode,
            userLoginName: ownerUserLoginName,
            userToken: token,
            delegateCertificateId,
            delegateUserLoginName: userLoginName,
          },
        });
        window.location.reload();
      }
    },

    //退出用户代理
    *delegateLogout({ payload }, { call, put, select }) {
      const {
        delegateCertificateId: _delegateCertificateId,
        delegateUserLoginName,
      } = yield select((state) => state.login);
      let localUserIdentity: any = localStorage.getItem("userIdentity");
      let _localUserIdentity = JSON.parse(localUserIdentity);
      let delegateCertificateId =
        _localUserIdentity &&
        _localUserIdentity.hasOwnProperty("delegateCertificateId")
          ? _.get(_localUserIdentity, "delegateCertificateId")
          : _delegateCertificateId;
      const delegateMode = false;
      const response = yield call(delegateLogout, {
        delegateCertificateId,
      });
      if (response) {
        const token = response.token;
        yield put({
          type: "writeToLocalStorage",
          payload: {
            delegateMode,
            userLoginName: delegateUserLoginName,
            userToken: token,
            delegateCertificateId: undefined,
            delegateUserLoginName: undefined,
          },
        });
        window.location.reload();
      }
    },
    // 退出
    *logout(_, { put }) {
      logoutByChain();
    },
  },
  reducers: {
    save(state, { payload }: any) {
      return { ...state, ...payload };
    },
  },
};
export default login;
